package com.sunseen.capacitormachine.modules.log;

import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.databinding.ViewDataBinding;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.sunseen.capacitormachine.R;
import com.sunseen.capacitormachine.common.BaseFragment;
import com.sunseen.capacitormachine.commumication.http.HttpUtil;
import com.sunseen.capacitormachine.commumication.http.RestClient;
import com.sunseen.capacitormachine.data.DataUtil;
import com.sunseen.capacitormachine.databinding.FragmentQueryAlarmLogBinding;
import com.sunseen.capacitormachine.modules.log.adapter.AlarmDetailAdapter;
import com.sunseen.capacitormachine.modules.log.adapter.AlarmLogAdapter;
import com.sunseen.capacitormachine.modules.log.bean.AlarmInfoBean;
import com.sunseen.capacitormachine.modules.log.event.QueryLogEvent;
import com.sunseen.capacitormachine.modules.log.event.RefreshLogListEvent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class QueryAlarmLogListFragment extends BaseFragment {
    @Override
    protected int setLayout() {
        return R.layout.fragment_query_alarm_log;
    }


    private FragmentQueryAlarmLogBinding binding;
    private AlarmLogAdapter adapter;

    @Override
    protected void onBindView(ViewDataBinding viewDataBinding) {
        binding = (FragmentQueryAlarmLogBinding) viewDataBinding;
        binding.alarmLogQueryRv.setLayoutManager(new LinearLayoutManager(_mActivity));
        adapter = new AlarmLogAdapter(R.layout.layout_item_alarm_log);
        adapter.bindToRecyclerView(binding.alarmLogQueryRv);
        adapter.setEnableLoadMore(true);
        adapter.setLoadMoreView(new LogDateLoadMoreView());
        adapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                if (curPage == lastPage) {
                    if (fragmentShowing) {
                        Toast.makeText(_mActivity, "该日期的操报警志已全部加载", Toast.LENGTH_SHORT).show();
                    }
                    adapter.loadMoreEnd(true);
                } else {
                    queryLogs(startTime, endTime, curPage + 1, false);
                }
            }
        }, binding.alarmLogQueryRv);
        adapter.disableLoadMoreIfNotFullPage();
        adapter.setOnItemClickListener((BaseQuickAdapter adapter, View view, int position) -> {
            AlarmInfoBean alarmInfoBean = (AlarmInfoBean) adapter.getData().get(position);
            showPopupWindow(alarmInfoBean);
        });
        EventBus.getDefault().register(this);
    }

    private long startTime;
    private long endTime;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onQueryLog(QueryLogEvent event) {
        if (event.getLogType() == 0) {
            this.startTime = event.getStartTimeStamp();
            this.endTime = event.getEndTimeStamp();
            queryLogs(startTime, endTime, 1, true);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRefreshLogList(RefreshLogListEvent event) {
        if (event.getPos() == 3) {
            if (startTime > 0) {
                queryLogs(startTime, endTime, 1, true);
            } else {
                Toast.makeText(_mActivity, "请输入正确的查询日期", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private int curPage = 0;
    private int lastPage = 0;

    private void queryLogs(long startTime, long endTime, int page, boolean refresh) {
        RestClient.builder()
                .url(HttpUtil.AlarmLog)
                .params("deviceNo", DataUtil.DeviceNo)
                .params("start_time", startTime)
                .params("end_time", endTime)
                .params("platform", 1)
                .params("userId", 1)
                .params("page", page)
                .success((String response) -> {
                    Log.e("test", "queryAlarmLogs: success ");
                    JSONObject rootObj = JSON.parseObject(response);
                    int status = rootObj.getIntValue("status");
                    if (status == 1) {
                        JSONObject dataObj = rootObj.getJSONObject("data");
                        curPage = dataObj.getIntValue("current_page");
                        List<AlarmInfoBean> alarmInfoBeanList = dataObj.getJSONArray("data")
                                .toJavaList(AlarmInfoBean.class);
                        if (!alarmInfoBeanList.isEmpty()) {
                            if (refresh) {
                                adapter.setNewData(alarmInfoBeanList);
                                lastPage = dataObj.getIntValue("last_page");
                            } else {
                                adapter.addData(alarmInfoBeanList);
                                adapter.loadMoreComplete();
                            }
                        } else {
                            Toast.makeText(_mActivity, "操作日志数据返回为空", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Toast.makeText(_mActivity, "操作日志数据返回状态码0", Toast.LENGTH_SHORT).show();
                    }
                })
                .failure(() -> {
                    Toast.makeText(_mActivity, "操作日志数据请求失败", Toast.LENGTH_SHORT).show();
                    Log.e("test", "queryLogs: failure");
                })
                .error((int code, String msg) -> {
                    Toast.makeText(_mActivity, "操作日志数据返回错误:" + msg, Toast.LENGTH_SHORT).show();
                    Log.e("test", "queryLogs: error" + msg);
                })
                .build()
                .get();
    }

    private PopupWindow popupWindow;
    private TextView alarmDateTv;
    private AlarmDetailAdapter alarmDetailAdapter;

    private void initPopupWindow() {
        popupWindow = new PopupWindow(_mActivity);
        View popupView = LayoutInflater.from(_mActivity).inflate(R.layout.layout_popup_alarm_log, null);
        popupWindow.setContentView(popupView);
        popupWindow.setWidth(1120);
        popupWindow.setHeight(720);
        popupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.cb_bg_gray_light));
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(false);
        popupWindow.update();

        alarmDateTv = popupView.findViewById(R.id.date_tv);
        RecyclerView alarmDetailRv = popupView.findViewById(R.id.alarm_rv);
        alarmDetailRv.setLayoutManager(new LinearLayoutManager(_mActivity));
        alarmDetailAdapter = new AlarmDetailAdapter(R.layout.layout_item_alarm_log_detail);
        alarmDetailAdapter.setOnItemClickListener((adapter, view, position) -> {
        });
        alarmDetailRv.setAdapter(adapter);
        Button hideBtn = popupView.findViewById(R.id.hide_btn);
        hideBtn.setOnClickListener((v) -> {
            popupWindow.dismiss();
        });

    }

    private View fragmentRootView;
    private DateFormat dateFormat;

    private void showPopupWindow(AlarmInfoBean alarmInfo) {
        if (popupWindow == null) {
            dateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
            initPopupWindow();
            fragmentRootView = LayoutInflater.from(_mActivity).inflate(R.layout.fragment_query_alarm_log, null);
        }
        String[] infos = alarmInfo.getAlarmInfo().split("、");
        List<String> details = new ArrayList<>();
        for (String str : infos) {
            details.add(str);
        }
        alarmDateTv.setText(dateFormat.format(new Date(alarmInfo.getTime() * 1000)) + "报警日志");
        alarmDetailAdapter.setNewData(details);
        popupWindow.showAsDropDown(fragmentRootView, 300, 68, Gravity.CENTER);
    }

    private boolean fragmentShowing = true;

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        fragmentShowing = !hidden;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }
}
